package com.nifostasky.main.terminal;

import java.io.*;
import java.util.Objects;
import java.util.Scanner;

/**
 * version: 1 : 目前版本存在bug;今后慢慢修复
 *
 * 与操作系统进行交互
 *
 * 这里的内存是程序内存的内存中 输出是 操作系统的终端(cmd/linux)命令行中
 * 所以此时: 程序内存的内存中 -> 操作系统的终端(cmd/linux)命令行中 : 输出流
 *         操作系统的终端(cmd/linux)命令行中 -> 程序内存的内存中 : 输入流
 */
public class InteractiveCase {

    public void InteractiveTest() throws IOException {
        //执行命令类
        Process process = Runtime.getRuntime().exec("cmd");
        /**
         * 将程序内存中的数据 输出到 操作系统cmd命令窗口中
         * 执行窗口中输入的命令
         */
        new Thread(() -> {
            //保存输入的命令
            String command = null;
            BufferedWriter writer = null;
            //获取输入内容 输入Q,q退出
            while(!"q".equals(command) || !"Q".equals(command)){
                //重置数据
                command = null;
                Scanner scanner = new Scanner(System.in);
                try {
                    //获取输入内容
                    command = scanner.nextLine();

                    //将输入内容 输出到 命令窗口中;
                    writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
                    writer.write(command);
                    writer.newLine();

                    writer.flush();

                }catch (IOException e){
                    e.printStackTrace();
                }

            }
            //关闭输出流
            try {
                if (Objects.nonNull(writer))
                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }).start();

        /**
         * 获取执行的命令结果内容;
         */
        new Thread(() -> {
            try{
                //输出控制台中显示的内容
                BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String cmdout = "";
                while ((cmdout = br.readLine()) != null) {
                    System.out.println("|| "+cmdout);
                }

            }catch (IOException e){
                e.printStackTrace();
            }

        }).start();

    }

    public static void main(String[] args) throws IOException {
        System.out.println("\n"+"=======================================================================================================================");
        InteractiveCase interactiveCase = new InteractiveCase();
        interactiveCase.InteractiveTest();
        System.out.println("======================================================================================================================="+"\n");

    }
}
